package com.d3works.apps.supplierportal.web;

import com.d3works.apps.base.db.Product;
import com.d3works.apps.supplierportal.db.ProductSupplier;
import com.d3works.apps.supplierportal.db.repo.ProductSupplierRepository;
import com.d3works.apps.supplierportal.service.ProductSupplierService;
import com.d3works.exception.ResponseMessageType;
import com.d3works.exception.service.TraceBackService;
import com.d3works.i18n.I18n;
import com.d3works.inject.Beans;
import com.d3works.meta.schema.actions.ActionView;
import com.d3works.rpc.ActionRequest;
import com.d3works.rpc.ActionResponse;

public class ProductSupplierController {

  public void addOnCatalog(ActionRequest request, ActionResponse response) {
    ProductSupplier productToAdd = request.getContext().asType(ProductSupplier.class);
    productToAdd = Beans.get(ProductSupplierRepository.class).find(productToAdd.getId());
    try {
      Product newProduct = Beans.get(ProductSupplierService.class).addOnCatalog(productToAdd);
      if (newProduct != null) {
        response.setView(
            ActionView.define(I18n.get("Product"))
                .model(Product.class.getName())
                .add("form", "product-form")
                .param("forceEdit", "true")
                .context("_showRecord", newProduct.getId())
                .map());
      }
    } catch (Exception e) {
      TraceBackService.trace(response, e, ResponseMessageType.ERROR);
    }
  }
}
